//
//  MeViewController.m
//  Haliaeetus
//
//  Created by junli hou on 2018/3/20.
//  Copyright © 2018年 BMY. All rights reserved.
//

#import "MeViewController.h"
#import "LoginManager.h"
#import "UIScrollView+VGParallaxHeader.h"
#import "MeTableViewCell.h"
#import "PersonInfoViewController.h"
#import "PayInfoViewController.h"
#import "RecordsViewController.h"
#import "NoticeViewController.h"
#define HEAD_HEIGHT 291

static NSString *const kDefaltCell = @"cell";


@interface MeViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *loginBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIImageView *headImg;
@property (nonatomic, strong) UILabel *userName;
@property (nonatomic, strong) UILabel *balance;
@property (nonatomic, strong) NSDictionary *userDic;
@property (nonatomic, strong) NSDictionary *creditCardDic;
@property (nonatomic, strong) NSMutableArray *transactionRecords;
@end
@implementation MeViewController
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.backgroundColor = WS_RGB(248, 248, 248);
        //        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
    }
    return _tableView;
}

- (void)updateLoginState
{

    
    if ([LoginManager getUserLoginStatus]) {
         [self getShopInfo];
    }else{
        [self setHeadContent];
        [self.tableView reloadData];
    }
}


- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    
    if ([LoginManager getUserLoginStatus]) {
        [self getShopInfo];
    }else{

        
        [self setHeadContent];
        [self.tableView reloadData];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];


    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.left.equalTo(self.view.mas_left);
        make.right.equalTo(self.view.mas_right);
        make.bottom.equalTo(self.view.mas_bottom).offset(-49);
    }];
    [self setHeadView];
    
}



- (void)setHeadView
{
    //    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0,0,ScreenWidth,HEAD_HEIGHT)];
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor clearColor];
    
    //bgView
    UIImageView *imageBg = [[UIImageView alloc]init];
    imageBg.frame=CGRectMake(0, 0, WS_SCREEN_FRAME_WIDTH, 200);
    imageBg.image = [UIImage imageNamed:@"me_header"];
    imageBg.backgroundColor = [UIColor clearColor];
     [headView addSubview:imageBg];
    //头像
    self.headImg = [[UIImageView alloc]init];
    self.headImg.frame = CGRectMake((WS_SCREEN_FRAME_WIDTH-110)/2,76,110,110);
    self.headImg.layer.cornerRadius = 110/2;
    self.headImg.layer.masksToBounds = YES;
    self.headImg.image = [UIImage imageNamed:@"header_icon"];
    self.headImg.backgroundColor = [UIColor clearColor];
    [headView addSubview:self.headImg];
    
    //登录按钮
    self.loginBtn = [[UIButton alloc]init];
    self.loginBtn.frame =CGRectMake(WS_SCREEN_FRAME_WIDTH/2-65,CGRectGetMaxY(self.headImg.frame) + 20,130,40);
    self.loginBtn.layer.cornerRadius=2;
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.backgroundColor = WS_RGB(255, 134, 35);
    self.loginBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [self.loginBtn setTitleColor:WS_RGB(255, 255, 255) forState:UIControlStateNormal];
    [self.loginBtn setTitle:@"点击登录" forState:UIControlStateNormal];
    [self.loginBtn addTarget:self action:@selector(login) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:self.loginBtn];
    
    self.userName = [[UILabel alloc]init];
    self.userName.frame =CGRectMake(30,CGRectGetMaxY(self.headImg.frame) + 20,WS_SCREEN_FRAME_WIDTH - 60,40);
    self.userName.text = @"";
    self.userName.textColor = WS_RGB(68, 69, 60);
    self.userName.font =  [UIFont systemFontOfSize:24];
    self.userName.textAlignment = NSTextAlignmentCenter;
    self.userName.backgroundColor = [UIColor clearColor];
    [headView addSubview:self.userName];
    
    self.balance = [[UILabel alloc]init];
    self.balance.frame =CGRectMake(30,CGRectGetMaxY(self.userName.frame) ,WS_SCREEN_FRAME_WIDTH - 60,40);
    self.balance.text = @"";
    self.balance.textColor = WS_RGB(140,140,135);
    self.balance.font =  [UIFont systemFontOfSize:10];
    self.balance.textAlignment = NSTextAlignmentCenter;
    self.balance.backgroundColor = [UIColor clearColor];
    [headView addSubview:self.balance];
    
    if ([LoginManager getUserLoginStatus]) {
        self.loginBtn.hidden = YES;
        self.userName.hidden = NO;
        self.balance.hidden=NO;
    }else{
        self.loginBtn.hidden = NO;
        self.userName.hidden = YES;
        self.balance.hidden=YES;
    }
    
    [self.tableView setParallaxHeaderView:headView mode:VGParallaxHeaderModeFill height:HEAD_HEIGHT];
    self.tableView.parallaxHeader.stickyViewPosition = VGParallaxHeaderStickyViewPositionBottom;
    [self.tableView.parallaxHeader setStickyView:headView
                                      withHeight:HEAD_HEIGHT];
//
    [self setHeadContent];
}

- (void)setHeadContent
{
    if ([LoginManager getUserLoginStatus]) {

        
        self.loginBtn.hidden = YES;
        self.userName.hidden = NO;
           self.balance.hidden=NO;
        //头像
        [self.headImg sd_setImageWithURL:[NSURL URLWithString:[self.userDic objectForKey:@"avatar_url"]] placeholderImage:[UIImage imageNamed:@"header_icon"]];

        //用户姓名
        self.userName.text =  [self.userDic objectForKey:@"nickname"];
        self.balance.text=[NSString stringWithFormat:@"账户余额：%@",WS_STR_NOT_NULL([self.userDic objectForKey:@"balance"])];

    }else{

        self.headImg.image = [UIImage imageNamed:@"header_icon"];
        
        self.loginBtn.hidden = NO;
        self.userName.hidden = YES;
        self.balance.hidden=YES;
        
    }
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // This must be called in order to work
    [self.tableView shouldPositionParallaxHeader];
    
    // This is how you can implement appearing or disappearing of sticky view
    //    [self.tableView.parallaxHeader.stickyView setAlpha:scrollView.parallaxHeader.progress];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([LoginManager getUserLoginStatus]) {
      return 4;
    }else{
         return 3;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row<3) {
        MeTableViewCell *cell;
        cell = [tableView dequeueReusableCellWithIdentifier:kDefaltCell];
        if (!cell) {
            cell = [[MeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDefaltCell];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        if (indexPath.row==0) {
            cell.iconImageView.image=[UIImage imageNamed:@"personInfo"];
            cell.titleLabel.text=@"个人信息";
            cell.desLabel.text=@"补充完整个人信息将自动填写预定信息";
            
        }else if (indexPath.row==1){
            cell.iconImageView.image=[UIImage imageNamed:@"pay"];
            cell.titleLabel.text=@"支付信息";
            cell.desLabel.text=@"填写支付信息将自动填写预定信息";
            
        }else if (indexPath.row==2){
            cell.iconImageView.image=[UIImage imageNamed:@"history"];
            cell.titleLabel.text=@"账户历史";
            cell.desLabel.text=@"最近一个月";
            
        }
        
        return cell;
    }else{
        static NSString *identifier = @"logoutCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        //
        UIButton *logoutBtn = (UIButton *)[cell viewWithTag:200];
        if (!logoutBtn) {
            logoutBtn = [[UIButton alloc]init];
            logoutBtn.backgroundColor = [UIColor whiteColor];
            logoutBtn.tag = 200;

            [logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
            [logoutBtn setTitleColor:WS_RGB(255, 134, 35) forState:UIControlStateNormal];
            logoutBtn.titleLabel.font = [UIFont systemFontOfSize:15 ];
            [logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
            [cell addSubview:logoutBtn];
        }
        [logoutBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(cell.mas_top).offset(0);
            make.left.equalTo(cell.mas_left);
            make.right.equalTo(cell.mas_right);
            make.height.equalTo(@50);
        }];
        
        return cell;
    }



}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==3) {
          return 60;
    }else{
          return 90;
    }
    


}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row==0) {

        
        if ([LoginManager getUserLoginStatus]) {
            PersonInfoViewController *personInfoVc=[[PersonInfoViewController alloc]initWithEditSuccessBlock:^{
                [self getShopInfo];
            }];
            personInfoVc.hidesBottomBarWhenPushed=YES;
            personInfoVc.userInfoDic=self.userDic;
            [self.navigationController pushViewController:personInfoVc animated:YES];
        }else{
            
            
            [self login];
        }
        
        
        
    }else if(indexPath.row==1){

        
        
        if ([LoginManager getUserLoginStatus]) {
            PayInfoViewController *payInfoVc=[[PayInfoViewController alloc]initWithPayInfoSuccessBlock:^{
                [self getShopInfo];
            }];
            payInfoVc.hidesBottomBarWhenPushed=YES;
            payInfoVc.payInfoDic=self.creditCardDic;
            [self.navigationController pushViewController:payInfoVc animated:YES];
        }else{
            
            
            [self login];
        }
        
        
        
    }else if(indexPath.row==2){
        
        
        
        if ([LoginManager getUserLoginStatus]) {
        RecordsViewController *recordsVc=[[RecordsViewController alloc]init];
        recordsVc.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:recordsVc animated:YES];
        }else{
            
            
            [self login];
        }
        

        

        
    }
    
}

-(void)logout{
    UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:nil message:[NSString stringWithFormat:@"%@",@"确定退出当前账号？"] preferredStyle:UIAlertControllerStyleAlert];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //退出登录
        [LoginManager logOut];
        self.userDic =NULL;
        self.creditCardDic = NULL;
        self.transactionRecords = NULL;
        
        [self.tableView reloadData];
        [self setHeadContent];
        

    }]];
    [alertControl addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alertControl animated:YES completion:nil];
    
}

#pragma mark - getShopInfo
- (void)getShopInfo
{

    [SVProgressHUD showWithStatus:@"loading"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    [WSNetwork WSHttpsByType:@"GET" Url:[NSString stringWithFormat:@"%@%@",BMY_URL,@"/profile"] params:NULL onCompletion:^(NSMutableDictionary *dic){
        [SVProgressHUD dismiss];
        
        if ([[dic objectForKey:@"biz_action"] intValue] == 0) {

            self.userDic = [[dic objectForKey:@"data"] objectForKey:@"profile"];
            self.creditCardDic = [[dic objectForKey:@"data"] objectForKey:@"credit_card"];
            self.transactionRecords = [[dic objectForKey:@"data"] objectForKey:@"transaction_records"];
  
            [self.tableView reloadData];
                [self setHeadContent];
        }else{
            
            //请求出错
            WSToast([dic objectForKey:@"biz_msg"]);
        }
    } onError:^(NSError *error) {
        
        if (error.code==99999) {
            WSToast(@"网络异常，请检查网络设置!");
        }
        [SVProgressHUD dismiss];
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)login{

    LoginViewController *loginController = [[LoginViewController alloc] initWithLoginSuccessBlock:^{

    } :^{

    }];
    [self presentViewController:[[BaseNavigationController alloc] initWithRootViewController:loginController] animated:YES completion:nil];

}
@end
